<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref } from 'vue'
import {
    scheduleCategoryListService,
    scheduleDeleteService,
    scheduleListService,
} from "@/api/schedule.js";
import { ElMessage, ElMessageBox } from "element-plus"
import ScheduleDrawer from "@/views/schedule/ScheduleDrawer.vue";

// 日程分类数据模型，添加更多分类
const categories = ref([
    {
        "id": 1,
        "categoryName": "工作",
        "categoryAlias": "work",
        "createTime": "2023-09-01 12:06:59",
        "updateTime": "2023-09-01 12:06:59"
    }
])
// 用户搜索时选中的发布状态
const state = ref('')

// 用户搜索时选中的分类id
const categoryId = ref('')

// 用户搜索时选中的日程状态
const scheduleState = ref('')

// 用户搜索时选中的日程紧急程度
const emergencyDegree = ref('');

// 新增搜索关键字
const keyword = ref('')

// 日程类型数据模型，初始化数据
const scheduleTypes = ref([
    {
        "id": 1,
        "typeName": "重要紧急",
    },
    {
        "id": 2,
        "typeName": "重要不紧急",
    },
    {
        "id": 3,
        "typeName": "紧急不重要",
    },
    {
        "id": 4,
        "typeName": "不重要不紧急",
    }
])

// 日程列表数据模型，添加更多数据
const schedules = ref([
    {
        "id": 1,
        "title": "项目会议",
        "content": "内容",
        "state": 0,
        "emergencyDegree": 1,
        "categoryId": 2,
        "remindTime": "2023-09-03 11:55:30",
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    },
    {
        "id": 2,
        "title": "学习Vue",
        "content": "学习Vue 3的新特性",
        "state": 0,
        "emergencyDegree": 1,
        "categoryId": 2,
        "remindTime": "2023-09-04 10:00:00",
        "createTime": "2023-09-03 14:00:00",
        "updateTime": "2023-09-03 14:00:00"
    },
    {
        "id": 3,
        "title": "品尝美食",
        "content": "去尝试新的餐厅",
        "state": 0,
        "emergencyDegree": 1,
        "categoryId": 3,
        "remindTime": "2023-09-05 18:00:00",
        "createTime": "2023-09-03 16:00:00",
        "updateTime": "2023-09-03 16:00:00"
    }
])

// 分页条数据模型
const pageNum = ref(1) // 当前页
const total = ref(20) // 总条数
const pageSize = ref(5) // 每页条数

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    scheduleList()
}
// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    scheduleList()
}

// 回显日程分类
const scheduleCategoryList = async () => {
    let result = await scheduleCategoryListService();
    categories.value = result.data;
}

// 获取日程列表数据
const scheduleList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value ? categoryId.value : null,
        state: state.value ? state.value : null,
        emergencyDegree: emergencyDegree.value ? emergencyDegree.value : null,
        keyword: keyword.value || null // 添加搜索关键字参数
    }
    let result = await scheduleListService(params);

    // 渲染视图
    total.value = result.data.total;
    schedules.value = result.data.items;

    // 处理数据，给数据模型扩展一个属性 categoryName，分类名称
    for (let i = 0; i < schedules.value.length; i++) {
        let schedule = schedules.value[i];
        for (let j = 0; j < categories.value.length; j++) {
            if (schedule.categoryId === categories.value[j].id) {
                schedule.categoryName = categories.value[j].categoryName;
            }
        }
        // 处理类型名称
        for (let k = 0; k < scheduleTypes.value.length; k++) {
            if (schedule.emergencyDegree === scheduleTypes.value[k].id) {
                schedule.typeName = scheduleTypes.value[k].typeName;
            }
        }
    }
}

scheduleCategoryList();
scheduleList();

// 控制抽屉是否显示
const visibleDrawer = ref(false)
// 添加表单数据模型
const scheduleModel = ref({
    title: '',
    categoryId: '',
    emergencyDegree: '',
    remindTime: '',
    content: '',
    state: 0
})

// 定义变量，控制标题的展示
const title = ref("添加日程")

// 展示日程弹窗
const showDialog = (row) => {
    title.value = '编辑日程'
    scheduleModel.value = {
        ...row,
        id: row.id
    }

    visibleDrawer.value = true
}

// 添加日程
const addSchedule = (result) => {
    ElMessage.success(result.msg || '添加成功')
    window.location.reload()
}

// 更新日程
const updateSchedule = (result) => {
    ElMessage.success(result.msg || '修改成功')
    window.location.reload()
}

// 取消操作
const drawerCancel = () => {
    ElMessageBox.confirm('确定要关闭吗？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        visibleDrawer.value = false
        window.location.reload()
    }).catch(() => {
        ElMessage({ type: 'info', message: '取消操作' })
    })
}

// 初始化数据
scheduleCategoryList()
scheduleList()

const deleteSchedule = (row) => {
    // 提示用户，确认框
    ElMessageBox.confirm(
        '你确认要删除该日程信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 调用接口
                let result = await scheduleDeleteService(row.id);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                // 刷新列表
                await scheduleList();
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '删除失败，请稍后重试',
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

// 重置搜索条件
const resetFilters = () => {
    categoryId.value = ''
    scheduleState.value = ''
    emergencyDegree.value = ''
    keyword.value = ''
    scheduleList()
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>日程管理</span>
                <div class="extra">
                    <el-button type="primary" @click="title='添加日程';visibleDrawer=true">添加日程</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="日程分类：">
                <el-select placeholder="请选择" v-model="categoryId" style="width: 200px;">
                    <el-option
                        v-for="c in categories"
                        :key="c.id"
                        :label="c.categoryName"
                        :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="日程状态：">
                <el-select placeholder="请选择" v-model="scheduleState" style="width: 200px;">
                    <el-option label="未完成" :value="0"></el-option>
                    <el-option label="已完成" :value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="紧急程度：">
                <el-select placeholder="请选择" v-model="emergencyDegree" style="width: 200px;">
                    <el-option
                        v-for="t in scheduleTypes"
                        :key="t.id"
                        :label="t.typeName"
                        :value="t.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <!-- 新增搜索关键字输入框 -->
            <el-form-item label="关键字：">
                <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="scheduleList">搜索</el-button>
                <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 日程列表 -->
        <el-table :data="schedules" style="width: 100%">
            <el-table-column label="日程标题" width="400" prop="title"></el-table-column>
            <el-table-column label="类型" prop="typeName"></el-table-column>
            <el-table-column label="分类" prop="categoryName"></el-table-column>
            <el-table-column label="提醒时间" prop="remindTime"></el-table-column>
            <el-table-column label="状态">
                <!-- 根据状态值显示对应的文字 -->
                <template #default="{ row }">
                    <span v-if="row.state === 0">未完成</span>
                    <span v-else-if="row.state === 1">已完成</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteSchedule(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据"/>
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end"
        />
        <!-- 抽屉 -->
        <ScheduleDrawer
            v-model:visible="visibleDrawer"
            :title="title"
            :categories="categories"
            :scheduleTypes="scheduleTypes"
            :schedule-model="scheduleModel"
            @addSchedule="addSchedule"
            @updateSchedule="updateSchedule"
            @cancel="drawerCancel"
        />
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .editor {
        width: 100%;

        :deep(.ql-editor) {
            min-height: 200px;
        }
    }
}
</style>